from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                             QPushButton, QFrame, QProgressBar)
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal
from PyQt6.QtGui import QPixmap
import base64
from http_client import http_client
import requests
from utils.style_manager import StyleManager

class QRCodeWorker(QThread):
    """二维码获取工作线程"""
    qr_code_ready = pyqtSignal(dict)  # 二维码获取成功信号
    qr_code_error = pyqtSignal(str)   # 二维码获取失败信号
    
    def __init__(self, proxy_name: str = "", api_name: str = "get_qr_code_mac"):
        super().__init__()
        self.proxy_name = proxy_name
        self.api_name = api_name
    
    def run(self):
        """在子线程中获取二维码"""
        try:
            # 根据选择的接口调用不同的方法
            if self.api_name == "get_qr_code_car":
                # 使用car接口
                data = http_client.get_qr_code_car(
                    device_id="",
                    device_name="",
                    login_type="",
                    proxy_name=self.proxy_name
                )
            else:
                # 默认使用mac接口
                data = http_client.get_qr_code_mac(
                    device_id="",
                    device_name="",
                    login_type="",
                    proxy_name=self.proxy_name
                )
            
            # 发送成功信号
            self.qr_code_ready.emit(data)
            
        except Exception as e:
            # 发送错误信号
            self.qr_code_error.emit(str(e))

class QRCodeDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("微信扫码登录")
        self.setFixedSize(400, 500)
        self.setModal(True)
        
        # 初始化属性
        self.qr_code_data = None
        self.login_info = None  # 存储登录成功信息
        self.qr_worker = None  # 二维码获取工作线程
        self.current_proxy_name = ""  # 当前代理名称
        self.current_api_name = "get_qr_code_mac"  # 当前接口名称
        
        self.setup_ui()
        
        # 定时器用于检查登录状态
        self.check_timer = QTimer()
        self.check_timer.timeout.connect(self.check_qr_status)
        print("二维码对话框初始化完成，定时器已连接")  # 添加调试信息
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        # 标题
        title_label = QLabel("请使用微信扫描二维码登录")
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        StyleManager.set_label_style(title_label, "title")
        layout.addWidget(title_label)
        
        # 二维码显示区域
        self.qr_frame = QFrame()
        self.qr_frame.setFixedSize(200, 200)
        StyleManager.set_frame_style(self.qr_frame, "panel")
        qr_layout = QVBoxLayout(self.qr_frame)
        
        self.qr_label = QLabel("正在获取二维码...")
        self.qr_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        StyleManager.set_label_style(self.qr_label, "status-muted")
        qr_layout.addWidget(self.qr_label)
        
        layout.addWidget(self.qr_frame, alignment=Qt.AlignmentFlag.AlignCenter)
        
        # 等待进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        self.progress_bar.setRange(0, 0)  # 无限进度条
        
        # 状态信息
        self.status_label = QLabel("等待扫码...")
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        StyleManager.set_label_style(self.status_label, "status-info")
        layout.addWidget(self.status_label)
        
        layout.addWidget(self.progress_bar)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 刷新按钮
        self.refresh_btn = QPushButton("刷新二维码")
        self.refresh_btn.clicked.connect(self.refresh_qr_code)
        StyleManager.set_button_style(self.refresh_btn, "info")
        button_layout.addWidget(self.refresh_btn)
        
        # 取消按钮
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        StyleManager.set_button_style(self.cancel_btn, "danger")
        button_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(button_layout)
        
        # 自动获取二维码
        self.get_qr_code()
    
    def refresh_qr_code(self):
        """刷新二维码，使用当前保存的参数"""
        self.get_qr_code(self.current_proxy_name, self.current_api_name)
        
    def cleanup_worker(self):
        """清理工作线程"""
        if self.qr_worker:
            if self.qr_worker.isRunning():
                self.qr_worker.quit()
                if self.qr_worker.wait(3000):  # 等待最多3秒
                    pass
                else:
                    self.qr_worker.terminate()
                    if self.qr_worker.wait(2000):  # 再等待2秒确保终止
                        pass
                    else:
                        pass
            else:
                pass
            
            # 断开所有信号连接
            try:
                if self.qr_worker:
                    self.qr_worker.qr_code_ready.disconnect()
                    self.qr_worker.qr_code_error.disconnect()
                    self.qr_worker.finished.disconnect()
            except:
                pass  # 信号可能已经断开
            
            # 销毁线程对象
            if self.qr_worker:
                self.qr_worker.deleteLater()
                self.qr_worker = None
        
    def get_qr_code(self, proxy_name: str = "", api_name: str = "get_qr_code_mac"):
        """从API获取二维码（使用子线程）"""
        # 保存当前参数
        self.current_proxy_name = proxy_name
        self.current_api_name = api_name
        
        # 先销毁之前的线程
        self.cleanup_worker()
        
        # 显示等待界面
        self.show_loading_ui()
        
        # 创建并启动工作线程
        self.qr_worker = QRCodeWorker(proxy_name, api_name)
        self.qr_worker.qr_code_ready.connect(self.on_qr_code_ready)
        self.qr_worker.qr_code_error.connect(self.on_qr_code_error)
        self.qr_worker.finished.connect(self.on_worker_finished)
        self.qr_worker.start()
    
    def show_loading_ui(self):
        """显示加载界面"""
        self.status_label.setText("正在获取二维码...")
        self.qr_label.setText("正在获取二维码...")
        self.progress_bar.setVisible(True)
        self.refresh_btn.setEnabled(False)
        
        # 清除之前的二维码显示
        for i in reversed(range(self.qr_frame.layout().count())): 
            self.qr_frame.layout().itemAt(i).widget().setParent(None)
        
        # 重新添加加载标签
        self.qr_label = QLabel("正在获取二维码...")
        self.qr_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        StyleManager.set_label_style(self.qr_label, "status-muted")
        self.qr_frame.layout().addWidget(self.qr_label)
    
    def hide_loading_ui(self):
        """隐藏加载界面"""
        self.progress_bar.setVisible(False)
        self.refresh_btn.setEnabled(True)
    
    def on_worker_finished(self):
        """工作线程完成回调"""
        # 线程完成后自动清理
        if self.qr_worker and not self.qr_worker.isRunning():
            self.qr_worker.deleteLater()
            self.qr_worker = None
    
    def on_qr_code_ready(self, data):
        """二维码获取成功回调（在主线程中执行）"""
        self.hide_loading_ui()
        
        # 处理API响应格式
        if data.get('Success') == True and data.get('Code') == 1:
            # 获取二维码数据
            qr_data = data.get('Data', {})
            
            # 获取二维码base64数据
            qr_base64 = qr_data.get('QrBase64')
            qr_url = qr_data.get('QrUrl')
            uuid = qr_data.get('Uuid')
            expired_time = qr_data.get('ExpiredTime')
            device_id = data.get('DeviceId')
            
            if qr_base64:
                # 保存二维码数据用于后续检查
                self.qr_code_data = {
                    'uuid': uuid,
                    'device_id': device_id,
                    'expired_time': expired_time,
                    'qr_url': qr_url
                }
                
                # 显示二维码
                self.display_qr_code(qr_base64)
                
                # 开始检查登录状态
                print(f"开始检查二维码状态，UUID: {uuid}")  # 添加调试信息
                print(f"定时器状态: {self.check_timer.isActive()}")  # 检查定时器状态
                self.check_timer.start(5 * 1000)  # 每5秒检查一次
                print(f"定时器已启动，间隔: 5秒")  # 确认定时器启动
                
                # 显示过期时间信息
                if expired_time:
                    self.status_label.setText(f"请使用微信扫描二维码 (过期时间: {expired_time})")
                else:
                    self.status_label.setText("请使用微信扫描二维码")
            else:
                self.qr_label.setText("二维码数据格式错误")
                self.status_label.setText("API返回的数据中没有找到二维码")
        else:
            error_msg = data.get('Message', '未知错误')
            self.qr_label.setText("获取二维码失败")
            self.status_label.setText(f"API错误: {error_msg}")
    
    def on_qr_code_error(self, error_msg):
        """二维码获取失败回调（在主线程中执行）"""
        self.hide_loading_ui()
        self.qr_label.setText("获取二维码失败")
        self.status_label.setText(f"错误: {error_msg}")
    
    def display_qr_code(self, qr_data):
        """显示二维码"""
        try:
            # 清除之前的布局
            for i in reversed(range(self.qr_frame.layout().count())): 
                self.qr_frame.layout().itemAt(i).widget().setParent(None)
            
            # 创建QPixmap
            pixmap = QPixmap()
            
            # 尝试不同的数据格式
            if isinstance(qr_data, str):
                # 如果是base64字符串
                if qr_data.startswith('data:image'):
                    # 处理data URL格式
                    qr_data = qr_data.split(',')[1]
                
                try:
                    # 解码base64数据
                    image_data = base64.b64decode(qr_data)
                    pixmap.loadFromData(image_data)
                except:
                    # 如果不是base64，可能是URL
                    response = requests.get(qr_data, timeout=10)
                    if response.status_code == 200:
                        pixmap.loadFromData(response.content)
                    else:
                        raise Exception("无法加载二维码图片")
            else:
                # 如果是字节数据
                pixmap.loadFromData(qr_data)
            
            # 调整大小并显示
            scaled_pixmap = pixmap.scaled(180, 180, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
            
            # 添加二维码图像
            qr_image_label = QLabel()
            qr_image_label.setPixmap(scaled_pixmap)
            qr_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.qr_frame.layout().addWidget(qr_image_label)
            
            self.status_label.setText("请使用微信扫描二维码")
            
        except Exception as e:
            self.qr_label.setText("二维码显示失败")
            self.status_label.setText(f"显示错误: {str(e)}")
    
    def display_qr_code_from_bytes(self, image_bytes):
        """从字节数据显示二维码"""
        try:
            # 清除之前的布局
            for i in reversed(range(self.qr_frame.layout().count())): 
                self.qr_frame.layout().itemAt(i).widget().setParent(None)
            
            # 创建QPixmap
            pixmap = QPixmap()
            pixmap.loadFromData(image_bytes)
            
            # 调整大小并显示
            scaled_pixmap = pixmap.scaled(180, 180, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
            
            # 添加二维码图像
            qr_image_label = QLabel()
            qr_image_label.setPixmap(scaled_pixmap)
            qr_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.qr_frame.layout().addWidget(qr_image_label)
            
            self.status_label.setText("请使用微信扫描二维码")
            
        except Exception as e:
            self.qr_label.setText("二维码显示失败")
            self.status_label.setText(f"显示错误: {str(e)}")
    
    def check_qr_status(self):
        """检查登录状态"""
        print("定时器触发，开始检查二维码状态")  # 添加调试信息
        if not self.qr_code_data or not self.qr_code_data.get('uuid'):
            print("没有二维码数据或UUID，停止检查")  # 添加调试信息
            return
            
        try:
            # 使用HTTP客户端检查登录状态，传递UUID
            result = http_client.check_qr_status(self.qr_code_data['uuid'], self.qr_code_data['device_id'])
            
            print(f"检查二维码状态结果: {result}")  # 添加调试信息
            
            # 根据API响应格式处理登录状态
            if result.get('Success') == True:  # 请求成功
                data = result.get('Data', {})
                acct_sect_resp = data.get('acctSectResp', {})
                
                if acct_sect_resp:  # 登录成功，有账户信息
                    # 保存用户信息：userName、nickName、alias
                    self.login_info = {
                        'userName': acct_sect_resp.get('userName', ''),
                        'nickName': acct_sect_resp.get('nickName', ''),
                        'alias': acct_sect_resp.get('alias', ''),
                        'bindMobile': acct_sect_resp.get('bindMobile', ''),
                        'status': acct_sect_resp.get('status', 0)
                    }
                    print(f"登录成功，用户信息: {self.login_info}")  # 添加调试信息
                    self.status_label.setText("登录成功！")
                    self.check_timer.stop()
                    self.accept()  # 关闭对话框并返回登录信息
                else:
                    # 检查是否还在等待扫码
                    print("等待扫码中...")  # 添加调试信息
                    self.status_label.setText("请使用微信扫描二维码")
            else:
                # API请求失败
                error_msg = result.get('Message', '未知错误')
                print(f"检查二维码状态失败: {error_msg}")  # 添加调试信息
                self.status_label.setText(f"检查状态失败: {error_msg}")
            
        except Exception as e:
            print(f"检查二维码状态异常: {e}")  # 添加调试信息
            self.status_label.setText(f"检查状态异常: {str(e)}")
    
    def get_login_info(self):
        """获取登录成功信息"""
        return self.login_info
    
    def closeEvent(self, event):
        """关闭事件处理"""
        # 停止检查定时器
        if self.check_timer.isActive():
            self.check_timer.stop()
        
        # 销毁工作线程
        self.cleanup_worker()
        
        super().closeEvent(event)
    
    def reject(self):
        """取消按钮处理"""
        # 销毁工作线程
        self.cleanup_worker()
        
        super().reject() 